package com.suxin.http.request.intercept;

import com.alibaba.nacos.client.config.impl.Limiter;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.suxin.http.model.Header;
import com.suxin.http.model.RequestHttpEntity;
import com.suxin.http.response.HttpClientResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * @author Tang
 * @classname LimiterHttpClientRequestInterceptor
 * @description [ 这是一个检查的拦截器 ]
 * @date 2023/3/5 19:29
 */
public class LimiterHttpClientRequestInterceptor implements HttpClientRequestInterceptor {

    @Override
    public boolean isInterceptor(URI uri, String method, RequestHttpEntity requestHttpEntity) {
        final Object body = requestHttpEntity.getBody();
        String key = (body == null ? "" : JacksonUtils.toJson(body));
        return Limiter.isLimit(key);
    }

    @Override
    public HttpClientResponse intercept() {
        return new LimitResponse();
    }

    public static class LimitResponse implements HttpClientResponse {

        @Override
        public Header getHeaders() {
            return Header.newInstance();
        }

        @Override
        public InputStream getBody() throws IOException {
            return new ByteArrayInputStream("limit not request!".getBytes(StandardCharsets.UTF_8));
        }

        @Override
        public int getStatusCode() throws IOException {
            return 500;
        }

        @Override
        public String getStatusText() throws IOException {
            return "limit not request!";
        }

        @Override
        public void close() throws IOException {

        }
    }

}
